package com.shigen.demo.atguigu;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * LRU算法
 *
 * @author shigenfu
 * @date 2022/6/3 6:15 下午
 */
public class LRUDemo<K,V> extends LinkedHashMap<K,V> {

  private int capacity;

  public LRUDemo(int capacity) {
    // The iteration ordering method for this linked hash map: true for access-order, false for insertion-order.
    super(capacity, 0.75F, true);
    this.capacity = capacity;
  }

  public LRUDemo(int initialCapacity, float loadFactor) {
    super(initialCapacity, loadFactor);
  }

  @Override
  protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
    return super.size() > capacity;
  }

  public static void main(String[] args) {
    LRUDemo<Integer, String> lruDemo = new LRUDemo<Integer, String>(3);
    lruDemo.put(1, "aa");
    lruDemo.put(2, "bb");
    lruDemo.put(3, "cc");
    System.out.println(lruDemo.keySet());
    lruDemo.put(4, "cc");
    System.out.println(lruDemo.keySet());
    lruDemo.put(2, "cc");
    System.out.println(lruDemo.keySet());
    lruDemo.put(6, "cc");
    System.out.println(lruDemo.keySet());
  }

}
